import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      children:[
        {
          path: '',
          name: 'dashboard',
          component: () => import('../views/AboutView.vue'),
        },
        {
          path: '/Permissiondisplay',
          name: 'Permissiondisplay',
          component: () => import('../views/RBAC/Permissiondisplay.vue'),
        },

                {
          path: '/RolesList',
          name: 'RolesList',
          component: () => import('../views/RBAC/RolesList.vue'),
        },

        {
          path: '/UserinfoList',
          name: 'UserinfoList',
          component: () => import('../views/RBAC/UserinfoList.vue'),
        },
        {
          path: '/CommodityInfo',
          name: 'CommodityInfo',
          component: () => import('../views/Traceabilitymanagement/CommodityInfo.vue'),
        },

        {
          path: '/details/:id',
          name: 'Detailsinfo',
          component: () => import('../views/Traceabilitymanagement/Detailsinfo.vue'),
        },
        {
          path: '/traceability',
          name: 'Traceability',
          component: () => import('../views/TraceabilityView.vue'),
        },
      ]
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('Token')
  const userInfo = localStorage.getItem('userInfo')
  
  // 如果访问登录页面
  if (to.path === '/') {
    if (token && userInfo) {
      // 已登录，跳转到首页
      next('/home')
    } else {
      // 未登录，放行
      next()
    }
    return
  }
  
  // 其它页面，未登录则跳转到登录页
  if (!token || !userInfo) {
    // 清除可能存在的无效数据
    localStorage.removeItem('Token')
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    next('/')
  } else {
    next()
  }
})

export default router
